package com.sunny.ynhz.ui.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.just.library.AgentWeb;
import com.just.library.ChromeClientCallbackManager;
import com.sunny.ynhz.R;
import com.sunny.ynhz.app.Constants;
import com.sunny.ynhz.ui.ImageActivity;
import com.sunny.ynhz.ui.MainActivity;
import com.sunny.ynhz.utils.MD5Utils;
import com.sunny.ynhz.utils.SPUtil;
import com.sunny.ynhz.utils.ToastUtils;
import com.sunny.ynhz.utils.WXUtil;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by luao on 2017/8/30.
 */

public class BaseWebActivity extends AppBaseTranslationTitleBarActivity {
    @BindView(R.id.linearLayout)
    LinearLayout linearLayout;

    public AgentWeb mAgentWeb;
    private ChromeClientCallbackManager.ReceivedTitleCallback mCallback;
    private String url = "";
    private IWXAPI api;
    private WXMediaMessage msg;
    private String webTitle = "";
    public WebView mWebView;
    private Activity activity;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.Theme_Design_Light_NoActionBar);
        setContentView(R.layout.activity_base_web);
        setLeftImage(R.mipmap.close);
        ButterKnife.bind(this);
        activity = this;

        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        loadUrl(url);
        mCallback = (view, title) -> setWebTitle(title);
        if (url.indexOf("?") != -1) {
            url = url + "&token=" + MD5Utils.string2MD5((System.currentTimeMillis() * 5 - 1799) + "") + "&tokentime=" + System.currentTimeMillis();
        } else {
            url = url + "?token=" + MD5Utils.string2MD5((System.currentTimeMillis() * 5 - 1799) + "") + "&tokentime=" + System.currentTimeMillis();
        }
        mAgentWeb = AgentWeb.with(this)//传入Activity
                .setAgentWebParent(linearLayout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams ,第一个参数和第二个参数应该对应。
                .useDefaultIndicator()// 使用默认进度条
                .defaultProgressBarColor() // 使用默认进度条颜色
                .setReceivedTitleCallback(mCallback) //设置 Web 页面的 title 回调
                .createAgentWeb()//
                .ready()
                .go(url);
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new JavaScriptinterface(this));
        mWebView = mAgentWeb.getWebCreator().get();


    }

    public void setContentView(int resId) {
        super.setContentView(resId);

    }

    public void setWebTitle(String title) {
        setTitle(title);
        webTitle = title;
    }


    @Override
    public void onclickRightImage() {
        super.onclickRightImage();
        shareToWeChat("111", "111", "www.baidu.com");
    }

    void shareToWeChat() {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;

        msg = new WXMediaMessage(webpage);
        msg.title = webTitle;
        msg.description = "来自" + " " + SPUtil.get("roleNames", "") + " " + SPUtil.get("name", "") + " " + "的分享";
        Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        msg.thumbData = WXUtil.bmpToByteArray(thumb, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    private void shareToWeChat(String title, String description, String webpageUrl) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = webpageUrl;

        msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = description;
        Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        msg.thumbData = WXUtil.bmpToByteArray(thumb, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;

        api.sendReq(req);
    }


    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    public void loadUrl(String url) {
        this.url = url;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        long secondTime = System.currentTimeMillis();
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            } else {
                if (!((Activity) this instanceof MainActivity)) {
                    finish();
                } else {
                    if (secondTime - firstTime < 2000) {
                        System.exit(0);
                    } else {
                        ToastUtils.SingleToastUtil(BaseWebActivity.this, "再按一次退出程序");
                        firstTime = System.currentTimeMillis();
                    }
                    return true;
                }
            }
        }

        return true;
    }

    public void showUploadActivity(String path) {

    }


    public class JavaScriptinterface {
        Context context;

        public JavaScriptinterface(Context c) {
            context = c;
        }

        @JavascriptInterface
        public void shareWx(String title, String description, String webpageUrl) {
            shareToWeChat(title, description, webpageUrl);
        }

        /**
         * @param tag      log TAG
         * @param errorMsg 日志信息
         */
        @JavascriptInterface
        public void printErrorLog(String tag, String errorMsg) {
            Log.e(tag, errorMsg);
        }

        /**
         * @param msg Toast内容
         */
        @JavascriptInterface
        public void toastMsg(String msg) {
            Toast.makeText(activity, msg, Toast.LENGTH_LONG).show();
        }

        @JavascriptInterface
        public void showUploadActivity(String path) {
            BaseWebActivity.this.showUploadActivity(path);
        }

        @JavascriptInterface
        public void getNewsImgURL(String path,String path1) {
            String[] split = path.split(".,,.");

            String url = path;
            Intent intent = new Intent(BaseWebActivity.this, ImageActivity.class);
            intent.putExtra("pic_path", url);
            intent.putExtra("path",path1);
            startActivity(intent);

        }
    }


}
